<?php

namespace App\Http\Controllers\Home;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Models\Modelblock;
use App\Http\Models\Modelinit;
use App\Http\Models\Page;


class ModelController extends  Controller{


    public function parse($modelId,$modelName){
        //找到模块对应的类 解析自己参数 返回数据
        $className = "App\\Http\\Controllers\\Model\\".$modelName."Controller";

        if(class_exists($className)){
            $model = new $className();
            return $model->parse($modelId,$modelName);
        }

        return '<div style="width:100px;height:100px;background:#abc123;text-align: center;">init</div>';
    }

    public function delete($modelId){
        return response()->json(['state'=>'ok','message'=>'删除成功']);
    }

    public function edit($modelId){
        $model = Modelblock::where('modelid',$modelId)->first();
        if(!$model['modelname']){
            return '还没有配置该模块';
        }
        $modelName = $model['modelname'];
        $className = "App\\Http\\Controllers\\Model\\".$modelName."Controller";

        if(class_exists($className)){
            $model = new $className();
            return $model->edit($modelId);
        }

        return '这个就是编辑页面';
    }

    public function choice($modelId,$modelName){
        //查找模块是否存在
        $model = Modelinit::where('modelname',$modelName)->first();
        if(!$model){
            return response()->json(['state'=>'err','message'=>'后台没有该模块']);
        }

        //如果有 那么就查找下该id是否已经在数据库中了 如果不再就增加
        $modelblock = Modelblock::where('modelid',$modelId)->first();
        //已经设置模块且模块还是原来的模块 那么保持不变
        if($modelblock){
            if($modelblock['modelname'] != $modelName){
                Modelblock::where('modelid',$modelId)->update(['modelname'=>$modelName,'modelparam'=>$model['initparam']]);
            }
        }else{
            Modelblock::insert(['modelid'=>$modelId,'modelname'=>$modelName,'modelparam'=>$model['initparam']]);
        }
        return response()->json(['state'=>'ok','message'=>'操作成功']);
    }


    /**
     * 保存模版内容
     */
    public function save(Request $request){

        $title = $request->input('title');
        $content = $request -> input('content');
        $id = $request ->input('id');

        $page = Page::where('id',$id)->first();

        if($page){
           Page::where('id',$id)->update(['content'=>$content,'title'=>$title]);
        }else{
            $time = date('Y-m-d H:i:s',time());
            Page::insert(['title'=>$title,'content'=>$content,'created_at'=>$time,'updated_at'=>$time]);
        }

        return response()->json(['state'=>'ok','message'=>'操作成功']);
    }

}